﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.EntityFramework;
using System.ServiceModel.DomainServices.Server.ApplicationServices;
using System.Web.Security;

namespace DiagnosticCenter.Web
{
    [EnableClientAccess]
    public class AuthenticationService : LinqToEntitiesDomainService<DiagcenterEntities>, IAuthentication<tblUser>
    {
        private static tblUser DefaultUser = new tblUser
        {
            Login = string.Empty,
            Role = string.Empty
        };

        public tblUser Login(string userName, string password, bool isPersistent, string customData)
        {
            if (ValidateUser(userName, password))
            {
                FormsAuthentication.SetAuthCookie(userName, isPersistent);
                return GetUser(userName);
            }
            return null;
        }

        private bool ValidateUser(string username, string password)
        {
            return ObjectContext.tblUsers.Any(u => u.Login == username)
                && ObjectContext.tblUsers.Any(u => u.Password == password);
        }

        public tblUser Logout()
        {
            FormsAuthentication.SignOut();
            return DefaultUser;
        }

        public tblUser GetUser()
        {
            if ((ServiceContext != null) &&
                (ServiceContext.User != null) &&
                ServiceContext.User.Identity.IsAuthenticated)
            {
                return GetUser(ServiceContext.User.Identity.Name);
            }
            return DefaultUser;
        }

        private tblUser GetUser(string userName)
        {
            return ObjectContext.tblUsers.Include("tblGroup").First(u => u.Login == userName);
        }

        public void UpdateUser(tblUser user)
        {
            if ((ServiceContext.User == null) ||
                (ServiceContext.User.Identity == null) ||
                !string.Equals(ServiceContext.User.Identity.Name, user.Name, StringComparison.Ordinal))
            {
                throw new UnauthorizedAccessException("You are only authorized to modify your own profile.");
            }

            ObjectContext.tblUsers.AttachAsModified(user, ChangeSet.GetOriginal(user));
        }
    }

    public partial class tblUser : IUser
    {
        [DataMember]
        [Key]
        public string Name
        {
            get { return Login; }
            set { Login = value; }           
        }

        [DataMember]
        public IEnumerable<string> Roles
        {
            get { return Role.Split(','); }
            set { Role = string.Join(",", value.ToArray()); }
        }

    }
}